package com.cs.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;
import androidx.viewbinding.ViewBinding;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.cs.base.dialog.LoadingDialog;
import com.cs.base.permission.RxPermissions;
import com.cs.base.vm.BaseViewModel;


/**
 * 文件名:BaseFragment
 */

public abstract class BaseFragment<VM extends BaseViewModel, VB extends ViewBinding> extends Fragment implements View.OnClickListener{
    protected static String TAG;
    protected VM viewModel;
    //ViewBinding
    protected VB binding;
    protected Context context;
    protected FragmentActivity activity;
    //加载框
    private LoadingDialog loadingDialog;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = getViewBinding(inflater,container);
        viewModel = initViewModel();
        initObserve();
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = getActivity();
        initView();
        initData();
    }

    /**
     * 获取子类布局ViewBinding
     */
    protected abstract VB getViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container);

    /**
     * 初始化ViewModel
     */
    protected VM initViewModel(){return null;}

    /**
     * 监听当前ViewModel中 showDialog和error的值
     */
    private void initObserve() {
        if (viewModel == null) {
            return;
        }
        viewModel.setDialogObserver(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isShow) {
                if (isShow) {
                    showLoading();
                } else {
                    dismissLoading();
                }
            }
        });
        viewModel.setErrorObserver(this, new Observer<Object>() {
            @Override
            public void onChanged(Object obj) {
                showError(obj);
            }
        });
    }

    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 申请权限
     * @param permissions Manifest.permission.WRITE_EXTERNAL_STORAGE
     */
    protected void requestPermissions(int request,final String... permissions){
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions)
                .subscribe(granted -> {
                    onPermissions(request,granted,permissions);
                });
    }

    /**
     * 处理权限申请结果
     */
    protected void onPermissions(int request,boolean granted,final String... permissions){
        LogUtils.d(TAG,"request="+request,"granted="+granted,"permissions="+permissions);
    }

    @Override
    public void onClick(View v) {}

    /**
     * @param path 路由
     * @return
     */
    protected Postcard router(String path){
        //跳转并携带参数 /demo/ModuleActivity  获取参数getIntent()
        return ARouter.getInstance().build(path);
                /*.withLong("key1", 666L)
                .withString("key3", "888")
                .navigation();*/
    }
    /**
     * 显示加载框
     */
    protected void showLoading() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(context);
            loadingDialog.show();
        } else if(!loadingDialog.isShowing()){
            loadingDialog.show();
        }
    }

    /**
     * 隐藏加载框
     */
    protected void dismissLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    /**
     * 设置加载框提示
     * @param msg
     */
    protected void setLoadingMsg(String msg){
        if(loadingDialog != null){
            loadingDialog.setLoadingMsg(msg);
        }
    }

    /**
     * ViewModel发生了错误
     */
    protected void showError(Object obj){};

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}
